package com.bootdo.system.shiro;

import com.bootdo.cms.dao.MemberDao;
import com.bootdo.cms.domain.MemberDO;
import com.bootdo.common.config.ApplicationContextRegister;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.Map;

/**
 * @author KonBAI
 * @version 1.0
 * Create by 2019/12/18 02:26
 */
public class MemberRealm extends AuthorizingRealm {


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Map<String, Object> map = new HashMap<>(16);
        map.put("username", username);
        String password = new String((char[]) token.getCredentials());

        MemberDao memberMapper = ApplicationContextRegister.getBean(MemberDao.class);
        // 查询用户信息
        MemberDO member = memberMapper.list(map).get(0);

        // 账号不存在
        if (member == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        // 密码错误
        if (!password.equals(member.getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        // 账号锁定
        if (member.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(member, password, getName());
        return info;
    }
}
